/* 头部 */
import React, {Component} from 'react'
import {Row,Col} from 'antd'
import MemorizeUtil from '../../util/memorizeUtil'
import {getWeather} from '../../api'
import {formatDate} from '../../util/util'
import MenuList from '../../config/menuConfig'
import {withRouter} from 'react-router-dom'
import './index.less'

class Header extends Component {

  state={
    sysTime: formatDate(Date.now()),
    dayPictureUrl: '',
    weather: ''
  }

  /* Get Weather Data */
  Weather = async()=>{
    const {dayPictureUrl,weather} = await getWeather('北京')
    this.setState({
      dayPictureUrl,
      weather
    })
  }
  
  /* Get different titles of each page dynamically */
  Title = ()=>{
    const path = this.props.location.pathname
    for (var i = 0; i < MenuList.length; i++) {
      const item = MenuList[i];
      if(item.key===path){
        return item.title
      }else if(item.children){
        const cItem = item.children.find(cItem => cItem.key===path)
        if(cItem){
          return cItem.title
        }
      }
    }
  }

  /* Get Current Time */
  Time = ()=>{
    this.intervalID = setInterval(()=>{
      const sysTime = formatDate(Date.now())
      this.setState({
        sysTime
      })
    },1000)
  }
  
  
  componentWillUnmount(){
    clearInterval(this.intervalID)
  }

  componentDidMount(){
    this.Weather()
    this.Time()
  }

  render () {
    const {sysTime,dayPictureUrl,weather}=this.state
    const username = MemorizeUtil.user.username
    const title = this.Title()

    return (
      <div className='header'>
        <div className="header-top">
          <span>Hello,{username}</span>
          <a href="javascript:" style={{margin:10}}>Logout</a>
        </div>
        <Row className='header-bottom'>
          <Col span={4}>
            <span className="title">{title}</span>
          </Col>
          <Col span={20} className='weather'>
            <span className='date'>{sysTime}</span>
            <img src={dayPictureUrl} alt="WeatherPic" className='weather-img'/>
            <span className='weather-detail'>{weather}</span>
          </Col>
        </Row>
      </div>
    )
  }
}

export default withRouter(Header)